package cn.ai.utils;



import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.springframework.ai.document.Document;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class JavaMethodParser {
    public  List<Document> parseMethods(Path javaFile) throws IOException {
        List<Document> methods = new ArrayList<>();
        String source = Files.readString(javaFile);

        ASTParser parser = ASTParser.newParser(AST.JLS18);
        parser.setSource(source.toCharArray());
        CompilationUnit cu = (CompilationUnit) parser.createAST(null);

        cu.accept(new ASTVisitor() {
            @Override
            public boolean visit(MethodDeclaration method) {
                // 获取方法元数据
                int start = method.getStartPosition();
                int end = start + method.getLength();
                String methodCode = source.substring(start, end);

                // 获取所属类
                TypeDeclaration clazz = (TypeDeclaration) method.getParent();

                // 构建元数据
                Map<String, Object> metadata = new HashMap<>();
                metadata.put("class", clazz.getName().getIdentifier());
                metadata.put("method", method.getName().getIdentifier());
                metadata.put("file", javaFile.toString());

                methods.add(new Document(methodCode, metadata));
                return super.visit(method);
            }
        });
        return methods;
    }
}
